package com.xyulu.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xyulu.entity.SysUserEntity;
import com.xyulu.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @Author Xyulu
 * @Date 2021/4/12 23:09
 * @Version 1.0
 */
@Component
public class ShiroUtil {

    private static SysUserService userService;

    @Resource
    private SysUserService sysUserService;

    @PostConstruct
    public void init(){
        userService = sysUserService;
    }

    public static String getLocalUserName(){
        Subject subject = SecurityUtils.getSubject();
        String username = (String)subject.getPrincipal();
        SysUserEntity user = userService.getOne(Wrappers.<SysUserEntity>lambdaQuery()
                .eq(SysUserEntity::getPhone, username));
        if (user != null) {
            return user.getUsername();
        } else {
            return "";
        }
    }

    public static Integer getLocalUserId(){
        Subject subject = SecurityUtils.getSubject();
        String username = (String)subject.getPrincipal();
        SysUserEntity user = userService.getOne(Wrappers.<SysUserEntity>lambdaQuery()
                .eq(SysUserEntity::getPhone, username));
        if (user != null) {
            return user.getId();
        } else {
            return null;
        }
    }
}
